<template>
    <div class="upload-container" style="width: 100%">
        <SCButton @click="handleClick" :type="type">
            <slot>上传文件</slot>
            <input
                ref="uploadRef"
                type="file"
                :value="uploadFile"
                class="srcon-upload"
                @change="handleFileChange"
                :webkitdirectory="!notDirectory"
                :directory="!notDirectory"
            />
        </SCButton>
        <div class="filename-container" v-if="needDisplayFile && fileName">
            <img src="../assets/svg/file-text.svg" class="file-icon" /><div>{{ fileName }}</div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
const props = defineProps<{
    modelValue: File,
    type: string,
    needDisplayFile: boolean,
    notDirectory: boolean,
}>();
const emits = defineEmits(["update:modelValue", "change"]);
const uploadRef = ref();
const uploadFile = ref<File>();
const fileName = ref(props.modelValue?.name);
const handleClick = () => {
    uploadRef.value?.click();
};
const handleFileChange = () => {
    const files = [...uploadRef.value?.files];
    if(files) {
        const file = files[0];
        fileName.value = file.name;
        if(props.notDirectory) {
            emits("update:modelValue", file);
            emits("change", file);
        } else {
            emits("update:modelValue", files);
            emits("change", files);
        }
    } else {
        fileName.value = "";
    }
};
watch(() => props.modelValue, () => {
    if(!props.notDirectory) {
        if(!props.modelValue) {
            uploadFile.value = undefined;
        } else {
            uploadFile.value = props.modelValue;
        }
        return;
    }
    if(!props.modelValue) {
        fileName.value = "";
        uploadFile.value = undefined;
    } else {
        fileName.value = props.modelValue?.name;
        uploadFile.value = props.modelValue;
    }
});
</script>

<style lang="scss" scoped>
.upload-icon{
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-right: 4px;
}
.srcon-upload{
    display: none;
}
.upload-container{
    display: flex;
    align-items: center;
}
.filename-container{
    padding-left: 12px;
    display: flex;
    align-items: center;
    overflow: hidden;
    div {
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
    }
}
.file-icon{
    display: inline-block;
    width: 16px;
    height: 16px;
    opacity: 0.7;
    margin-right: 8px;
    vertical-align: middle;
    display: inline-flex;
    align-items: center;
}
</style>
